import { useEffect } from "react";

function useIntersectionObserver(
  setActiveId: React.Dispatch<React.SetStateAction<any>>,
  rootEl: Element | null
) {
  
    let nodeList:Element[] = []
    if(rootEl){
         nodeList = Array.from(rootEl.querySelectorAll("h2,h3"));
    }

  // must in the top level call useEffect  
  useEffect(() => {
    console.log("我running?2")
    const observer = new IntersectionObserver(callback,{
        rootMargin:'0px 0px -75% 0px'
    });
    nodeList.forEach((el) => observer.observe(el));
    console.log(nodeList)
    return () => observer.disconnect();
  }, [nodeList]); // 依赖它的变化因为完全nodeList会为[],需要等他初始化有内容



  function callback(entries: IntersectionObserverEntry[]) {
    const visiableHeadings: string[] = [];
    entries.forEach((entry) => {
        console.log(entries.length)
      if (entry.isIntersecting) {
        visiableHeadings.push(entry.target.id);
      }
    });
    console.log(visiableHeadings)
    if (visiableHeadings.length === 1) {
      setActiveId(visiableHeadings[0]);
    } else if (visiableHeadings.length > 0) {
      // 找到最前面的heading
      const sortHeadings = visiableHeadings.sort((a, b) => getIndexFromId(a) - getIndexFromId(b));
      console.log("排好序的headings"+sortHeadings)
      setActiveId(sortHeadings[0])
    } else {
      //不更新activeId，维持现状
    }
    // setActiveId()
  }

  function getIndexFromId(id:string){
    return nodeList.findIndex(node => node.id === id)
  }
}

export default useIntersectionObserver;
